package max.ta.download;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import max.ta.util.conf.SystemConfiguration;
import max.ta.util.file.FileHelper;

import org.apache.log4j.Logger;

public class ResourceDownloader {

    private static final Logger logger = Logger.getLogger(ResourceDownloader.class);
    // --------------------------------------------------------------------------------
    private static final String ROOT_DIR = SystemConfiguration.getRootDir();

    // --------------------------------------------------------------------------------


    public File downloadFile(URL url, String fileName) throws IOException {
	logger.info(">>> Donwload " + url + " to dir  : " + ROOT_DIR);
	BufferedReader in = null;
	try {
	    URLConnection conn = createConnection(url);
	    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    String inputLine = null;
	    StringBuffer sb = new StringBuffer();
	    while ((inputLine = in.readLine()) != null) {
		sb.append(inputLine + "\n");
	    }
	    File file = new File(ROOT_DIR + "/" + fileName);
	    FileHelper.writeText(sb.toString(), file);
	    logger.info(">>> Data saved at " + file.getAbsolutePath());
	    return file;
	} finally {
	    if (in != null) {
		in.close();
	    }
	}
    }

    private URLConnection createConnection(URL url) throws IOException {
	URLConnection connection = null;
	if (DownloaderProxy.isProxyConfigured()) {
	Proxy proxy = DownloaderProxy.getProxy();
	    connection = url.openConnection(proxy);
	} else {
	    connection = url.openConnection();
	}
	logger.debug(" ### Protocol : " + connection.getURL().getProtocol());
	logger.debug(" ### Host     : " + connection.getURL().getHost());
	logger.debug(" ### Port     : " + connection.getURL().getPort());
	return connection;
    }

}
